package org.lc.platform.base.util;

import jakarta.validation.ConstraintViolation;
import jakarta.validation.Validation;
import jakarta.validation.Validator;
import jakarta.validation.ValidatorFactory;
import org.lc.platform.base.exception.SystemException;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

public class BeanValidatorUtil {
    private static final ValidatorFactory VALIDATOR_FACTORY = Validation.buildDefaultValidatorFactory();

    //返回map
    public static <T> void validate(T t) {
        Validator validator = VALIDATOR_FACTORY.getValidator();
        Set<ConstraintViolation<T>> validateResult = validator.validate(t);
        if (!validateResult.isEmpty()) {
            List<String> errorsMsg = new ArrayList<>();
            validateResult.forEach(r -> {
                String msg = "字段:" + r.getPropertyPath().toString() + ",错误:" + r.getMessageTemplate();
                errorsMsg.add(msg);
            });
            throw new SystemException(String.join(";", errorsMsg));
        }
    }

}
